package com.hxt.framework.utils;

import java.util.Random;

import org.springframework.util.ObjectUtils;

/**
 * @ClassName: TokenUtil
 * @Description: token工具
 * @author: 
 * @date: 2016年10月18日 上午11:01:05
 */
public class TokenUtil
{

	/**
	 * 生成Token
	 * 
	 * @return
	 */
	public static String getToken()
	{
		String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		Random rnd = new Random();
		StringBuilder sb = new StringBuilder(30);
		for (int i = 0; i < 25; i++)
			sb.append(AB.charAt(rnd.nextInt(AB.length())));
		return sb.toString();
	}

	/**
	 * 生成Token
	 * 
	 * @return
	 */
	public static String getRandom(int length)
	{
		String AB = "0123456789";
		Random rnd = new Random();
		StringBuilder sb = new StringBuilder(length);
		for (int i = 0; i < length; i++)
			sb.append(AB.charAt(rnd.nextInt(AB.length())));
		return sb.toString();
	}

	public static String getTokenByUserId(Integer userID)
	{
		String userIDStr = String.valueOf(userID);
		String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		Random rnd = new Random();
		StringBuilder sb = new StringBuilder(30);
		// 获取用户ID长度
		Integer size = userIDStr.length();
		// 判断是否为偶数
		boolean even = size % 2 == 0 ? true : false;
		for (int i = 1, k = 0; i <= 30; i++)
		{
			if (size > k)
			{
				if (even)
				{
					if (i % 2 == 0)
					{
						sb.append(userIDStr.charAt(k));
						k++;
					} else
					{
						sb.append(AB.charAt(rnd.nextInt(AB.length())));
					}
				} else
				{
					if (i % 2 != 0)
					{
						sb.append(userIDStr.charAt(k));
						k++;
					} else
					{
						sb.append(AB.charAt(rnd.nextInt(AB.length())));
					}
				}
			} else
			{
				sb.append(AB.charAt(rnd.nextInt(AB.length())));
			}
		}
		sb.append(size);
		return sb.toString();
	}

	/**
	 * @Title: getUserIDByToken
	 * @Description: TODO
	 * @author: liw .
	 * @return Integer
	 */
	public static Integer getUserIdByToken(String token)
	{
		
		if (ObjectUtils.isEmpty(token))
		{
			return 0;
		}
		try
		{
			// 获取token最后一位
			Integer size = Integer.parseInt(String.valueOf(token.charAt(token.length() - 1)));
			int k = size % 2 == 0 ? 0 : 1;
			StringBuffer idBuff = new StringBuffer();
			for (int i = 1; i <= size; i++)
			{
				Integer index = i * 2 - k;
				idBuff.append(token.charAt(index - 1));
			}
			return Integer.parseInt(idBuff.toString());
		} catch (Exception e)
		{
			return 0;
		}
	}
}
